<script src="../bower_components/jxon/index.js"></script>
<link rel="import" href="../bower_components/polymer/polymer.html" />
<link rel="import" href="custom-button.html" />
<dom-module id="xiami-radio">
  <style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  
  *:focuse, *:active {
    outline: none;
  }
  
  :host {
    -webkit-user-select: none;
    user-select: none;
    font-family: "Helvetica Neue", Helvetica, "Nimbus Sans L", Arial, "Liberation Sans", "Hiragino Sans GB", "Source Han Sans CN", "Source Han Sans SC", "Microsoft YaHei", "Wenquanyi Micro Hei", "WenQuanYi Zen Hei", "ST Heiti", SimHei, "WenQuanYi Zen Hei Sharp", sans-serif;
    font-size: 12px;
  }
  
  .absolute {
    display: block;
    position: absolute;
  }
  
  #container {
    height: 180px;
    width: 720px;
    background-image: url("images/background.png");
    background-repeat: no-repeat;
    background-color: #000;
    color: #fff;
    text-shadow: 0 0 5px black;
  }
  
  section {
    background: -webkit-canvas(track-panel) no-repeat;
    /*
    background-image: url("images/track_panel.jpg"), url("images/track_panel_shadow.png");
    background-size: 540px 193px, contain;
    background-repeat: no-repeat;
    */
    height: 100%;
    width: 100%;
  }
  
  #album-cover {
    height: 100px;
    width: 100px;
    background-image: url("images/album_cover_blank.jpg");
    background-repeat: no-repeat;
    top: 36px;
    left: 36px;
  }
  
  #info {
    top: 36px;
    left: calc(36px + 100px + 4px);
    width: 344px;
    height: 100px;
    padding-left: 10px;
  }
  
  #control {
    top: 60px;
    right: 80px;
  }
  
  #share {
    right: 15px;
    bottom: 5px;
  }
  
  input[type="range"] {
    -webkit-appearance: none;
    width: 62px;
    height: 9px;
    background: transparent;
  }
  
  input[type="range"]::-webkit-slider-runnable-track {
    background: url("images/range_background.png");
    height: 9px;
  }
  
  input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none;
    background: url("images/range_block.png");
    width: 8px;
    height: 7px;
  }
  
  #title {
    font-size: 14px;
    font-weight: bold;
  }
  
  #artist {
    font-size: 14px;
  }
  
  #time-now {
    font-weight: bold;
  }
  
  #info-button {
    position: relative;
    top: 4px;
  }
  
  #like {
    bottom: 5px;
  }
  
  #like > * {
    margin-right: 10px;
  }
  
  #process {
    margin-top: 10px;
  }
  </style>
  <template>
    <div id="container" class="absolute">
      <section>
        <div id="album-cover" class="absolute">
          <img src="{{info.album_cover}}" />
        </div>
        <div id="info" class="absolute">
          <div id="name">
            <span id="title">{{info.song_name}}</span>
            <span>-</span>
            <span id="artist">{{info.artist_name}}</span>
            <custom-button id="info-button" on-click="getSongDetail" image-default="{{image.detail.normal}}" image-hover="{{image.detail.hover}}"></custom-button>
          </div>
          <div id="process">
            <span id="time-now">{{info.current_time}}</span>
            <span>/</span>
            <span id="time-total">{{info.total_time}}</span>
          </div>
          <div id="button-group">
            <div id="like" class="absolute">
              <custom-button on-click="likeSong" image-default="{{image.is_liked.normal}}" image-hover="{{image.is_liked.hover}}"></custom-button>
              <custom-button on-click="dislikeSong" image-default="{{image.unlike.normal}}" image-hover="{{image.unlike.hover}}"></custom-button>
            </div>
            <div id="share" class="absolute">
              <custom-button on-click="shareSong" image-default="{{image.share.normal}}" image-hover="{{image.share.hover}}"></custom-button>
              <custom-button on-click="addShowcollect" image-default="{{image.collect.normal}}" image-hover="{{image.collect.hover}}"></custom-button>
              <custom-button on-click="downloadSong" image-default="{{image.download.normal}}" image-hover="{{image.download.hover}}"></custom-button>
              <custom-button on-click="sendToPhone" image-default="{{image.phone.normal}}" image-hover="{{image.phone.hover}}"></custom-button>
            </div>
          </div>
        </div>
      </section>
      <div id="control" class="absolute">
        <div id="play">
          <custom-button on-click="controlPlayer" image-default="{{image.control.normal}}" image-hover="{{image.control.hover}}"></custom-button>
          <custom-button on-click="nextSong" image-default="{{image.next.normal}}" image-hover="{{image.next.hover}}"></custom-button>
        </div>
        <div id="volume">
          <custom-button on-click="mute" image-default="{{image.volume.normal}}"></custom-button>
          <input type="range" min="0" max="1" step="0.1" value="{{volume::change}}" />
        </div>
      </div>
    </div>
  </template>
</dom-module>
<script type="module">
(function(){
  'use strict'
  
  const IMAGES_PATH = `${document.currentScript.ownerDocument.origin}/elements/images`
  
  let images = {}
  
  function currying(fn, ...args) {
    return (...new_args) => fn.apply(this, args.concat(new_args))
  }
  
  function loadImages(...urls) {
    //const IMAGES_PATH = `${document.currentScript.ownerDocument.origin}/elements/images`
    
    function convertURLToImagePromise(url) {
      return new Promise(function(resolve, reject) {
        let img = new Image()
        
        let handler = currying(function(result, fn) {
          return function (){
            fn(result)
          }
        }, {url, img})
        
        img.addEventListener('load', handler(resolve))
        img.addEventListener('error', handler(reject))
        
        if (url.startsWith('chrome-extension://')) {
          img.src = url
        } else {
          img.src = `${IMAGES_PATH}/${url}`
        }
      })
    }
  
    let promise_list = urls.map(convertURLToImagePromise)
    
    return Promise.all(promise_list)
  }
  
  function applyMask(img, mask, ctx) {
    function apply(ctx) {
      ctx.save()
      try {
        ctx.drawImage(mask, 0, 0)
        ctx.globalCompositeOperation = 'source-in'
        ctx.drawImage(img, 0, 0)
      } catch(e) {
        console.log(img, mask)
      }
      ctx.restore()
    }
    
    if(ctx) {
      apply(ctx)
    } else {
      let canvas = document.createElement('canvas')
      ctx = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      apply(ctx)
      return canvas.toDataURL()
    }
  }
  
  let isString = (obj) => Object.prototype.toString.call(obj) === '[object String]',
    isArray = Array.isArray,
    isObject = (obj, type = typeof obj) => type === 'function' || type === 'object' && !!obj,
    isArrayOrObject = (obj) => isArray(obj) || isObject(obj)
  
  function convertToFullPath(obj) {
    if (! isArrayOrObject(obj)) {
      return
    }
    
    
    for(let key in obj) {
      if (isString(obj[key])) {
  	    obj[key] = `${IMAGES_PATH}/${obj[key]}`
    	} else {
    	  convertToFullPath(obj[key])
    	}
    }
  }
  
  function createImageFromDataURI(image_uri){
    let img = new Image()
    img.src = image_uri
    return img
  }
  
  // The -webkit-canvas CSS feature is deprecated in Chrome 44
  /*
  loadImages('track_panel.jpg', 'track_panel_shadow.png')
  .then(function(image_list) {
    image_list.forEach(({url, img}) => images[url] = img)
    
    ;(function() {
      let ctx = document.getCSSCanvasContext('2d', 'track-panel', 540, 193)
      applyMask(images['track_panel.jpg'], images['track_panel_shadow.png'], ctx)
    })()
  })
  */
  
  System.baseURL = document.currentScript.ownerDocument.origin
  
  Promise.all([
    System.import('elements/js/XiamiPlayer'),
    System.import('elements/js/image')
  ]).then(function([{XiamiPlayer},{image}]){
    //convertToFullPath(image)
    
    for(let i in image) {
      if(image[i].shadow) {
        for(let j in image[i]) {
          if(j == 'shadow' || !image[i][j].startsWith('data:image/jpeg')) {
            continue
          }
          
          image[i][j] = applyMask(createImageFromDataURI(image[i][j]), createImageFromDataURI(image[i].shadow))
        }
      }
    }
    
    let xiami_radio_scope,
      xiami_player = new XiamiPlayer(true)
    
    function isNumber(obj) {
      return !isNaN(obj)
    }
    
    function getPlaylist() {
      let type, id,
        current_url = new URL(document.URL),
        pathname_array = current_url.pathname.split('/'),
        parameter_array = (function() {
          let arr = []
          for(let i = 0; i < pathname_array.length; i++){
            if(pathname_array[i] && (isNumber(pathname_array[i]) || isNumber(pathname_array[i + 1]))) {
              arr.push(pathname_array[i])
            }
          }
          return arr
        })(),
        parameter = (function() {
          let obj = {}
          for(let i = 0; i < parameter_array.length; i += 2){
            obj[parameter_array[i]] = parameter_array[i + 1]
          }
          return obj
        })()
      
      if (parameter.type && parameter.oid){
        // normal radio:
        // http://www.xiami.com/radio/play/type/4/oid/11136270
        type = parameter.type
        id = parameter.oid
      } else if (parameter.id === '2') {
        // xiamicai:
        // http://www.xiami.com/radio/play/id/2
        type = 8
        id = 0
      } else {
        throw new Error('Unknown URL format')
      }
      
      let playlistAPI = `http://www.xiami.com/radio/xml/type/${type}/id/${id}`
      
      return new Promise((resolve, reject) => {
        let req = new XMLHttpRequest()
        req.open('GET', playlistAPI)
        req.onreadystatechange = () => {
          if (req.status === 200) {
            resolve(JXON.build(req.responseXML).playlist.tracklist.track)
          } else {
            reject(new Error(req.statusText))
          }
        }
        req.send()
      })
    }
    
    function loadPlaylist(){
      return new Promise((resolve, reject) => {
        getPlaylist().then((playlist) => {
          xiami_player.add(playlist)
          resolve()
        })
      })
    }
    
    function loadSong(){
      xiami_radio_scope.set('info.grade', !!xiami_player.current_track.grade)
      xiami_radio_scope.set('info.album_cover', xiami_player.current_track.pic)
      xiami_radio_scope.set('info.song_name', xiami_player.current_track.title)
      xiami_radio_scope.set('info.artist_name', xiami_player.current_track.artist)
    }
    
    xiami_player.audio_element.addEventListener('loadstart', function(){
      Fm_beforeplay({
        songName: xiami_player.current_track.title,
        artist: xiami_player.current_track.artist,
        artisId: xiami_player.current_track.artist_id
      })
    })
    
    xiami_player.audio_element.addEventListener('ended', function(){
      xiami_player.next()
      loadSong()
    })
    
    xiami_player.audio_element.addEventListener('progress', function(foo){
    })
    
    xiami_player.audio_element.addEventListener('timeupdate', function(foo){
      xiami_radio_scope.set('info.current_time', xiami_player.current_time_MMSS)
    })
    
    xiami_player.audio_element.addEventListener('loadedmetadata', function(foo){
      xiami_radio_scope.set('info.current_time', xiami_player.current_time_MMSS)
      xiami_radio_scope.set('info.total_time', xiami_player.total_time_MMSS)
    })
    
    Polymer({
      is: 'xiami-radio',
      ready: function(){
        xiami_radio_scope = this
        
        xiami_radio_scope.$$('#container section').style.backgroundImage = `url(${image.panel.normal})`
        
        xiami_radio_scope.set('image.volume', image.voice)
        xiami_radio_scope.set('info.current_time', '00:00')
        xiami_radio_scope.set('info.total_time', '00:00')
        
        xiami_player.addEventListener('PlayingStatusChange', ({detail: {isPaused}}) => {
          let play = image.play,
            pause = image.pause
          
          if(isPaused) {
            xiami_radio_scope.set('image.control', play)
          } else {
            xiami_radio_scope.set('image.control', pause)
          }
        })
        
        xiami_player.addEventListener('NextMusicIsntExist', function(){
          loadPlaylist().then(function(){
            xiami_player.next().play()
            loadSong()
          })
        })
        
        xiami_player.addEventListener('MusicLoading', ({detail: {info}}) => {
          let liked = image.liked,
            not_liked = image.like
          
          if(info.grade === 1) {
            xiami_radio_scope.set('image.is_liked', liked)
          } else {
            xiami_radio_scope.set('image.is_liked', not_liked)
          }
        })
        
        loadPlaylist().then(function(){
          xiami_player.load().play()
          loadSong()
        })
      },
      dislikeArtist: function(){
        player_unlike({
          artisId: xiami_player.current_track.artist_id
        })
      },
      likeSong: function(){
        player_collect({
          artisId: xiami_player.current_track.artist_id,
          songId: xiami_player.current_track.song_id
        })
        
        let liked = image.liked,
          not_liked = image.like
        
        if(xiami_player.current_track.grade === 1) {
          xiami_player.current_track.grade = -1
          xiami_radio_scope.set('image.is_liked', not_liked)
        } else {
          xiami_player.current_track.grade = 1
          xiami_radio_scope.set('image.is_liked', liked)
        }
      },
      dislikeSong: function(){
        Fm_trash({
          artisId: xiami_player.current_track.artist_id,
          songId: xiami_player.current_track.song_id
        })
        this.nextSong()
      },
      getSongDetail: function(){
        window.open(`http://www.xiami.com/song/${xiami_player.current_track.song_id}`, '_blank')
        // TODO: RadioClickTrigger recommend/log
      },
      shareSong: function(){
        recoomand(xiami_player.current_track.song_id, 32)
      },  
      addShowcollect: function(){
        collect(xiami_player.current_track.song_id)
      },
      downloadSong: function(){
        download(xiami_player.current_track.song_id)
      },
      sendToPhone: function(){
        Fm_send({
          songId: xiami_player.current_track.song_id
        })
      },
      controlPlayer: function(){
        if(xiami_player.isPaused()){
          xiami_player.play()
        } else {
          xiami_player.pause()
        }
      },
      nextSong: function(){
        if(xiami_player.isLastMusic()){
          loadPlaylist().then(function(){
            xiami_player.next()
            loadSong()
            //getHqSong(xiami_player.current_track.song_id).then(loadSong)
          })
        } else {
          xiami_player.next()
          loadSong()
        }
      },
      mute: function(){
        if(xiami_player.isMuted()){
          xiami_player.mute = false
          xiami_radio_scope.set('image.volume', image.voice)
        } else {
          xiami_player.mute = true
          xiami_radio_scope.set('image.volume', image.muted)
        }
      },
      volumeChanged: function(volume_value){
        xiami_player.volume = Number(volume_value)
      },
      properties: {
        volume: {
          type: Number,
          value: 1,
          notify: true,
          observer: 'volumeChanged'
        },
        info: {
          type: Object,
          value: {
            grade: '',
            album_cover: '',
            song_name: '',
            artist_name: ''
          }
        },
        image: {
          type: Object, 
          value: image
        }
      }
    })
  })
})()
</script>
<script>
(function processInclude() {
  'use strict'
  var doc = document.currentScript.ownerDocument,
    transcoder = new traceur.WebPageTranscoder(doc.URL),
    selector = 'script[type="module"],script[type="text/traceur"]',
    scripts = doc.querySelectorAll(selector)

  if (scripts.length) {
    transcoder.addFilesFromScriptElements(scripts, function() {})
  }
})()
</script>